﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Linq;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Controls;

namespace PRO_DOCS.DocumentManagementSystem.ADMIN.WIN.Configurations.Departments
{
    public partial class Departments : BLL.WIN.Templates.DevxConfigurationUserControlTemplate
    {

        private List<DAL.Database.ARCHIVE_DEPARTMENT> _aRCHIVE_DEPARTMENTS;
        private List<DAL.Database.ARCHIVE_DEPARTMENT> ARCHIVE_DEPARTMENTS
        {
            get { return _aRCHIVE_DEPARTMENTS; }
            set
            {
                _aRCHIVE_DEPARTMENTS = value;
                if (_aRCHIVE_DEPARTMENTS.Count > 0)
                {

                }
            }
        }

        private void RELOAD_ALL_ARCHIVE_DEPARTMENTS()
        {
            ARCHIVE_DEPARTMENTS = PRO_DOCSDatabaseDataContext.ARCHIVE_DEPARTMENTs.ToList();
            gridControl1.DataSource = ARCHIVE_DEPARTMENTS;

        }

        Dictionary<int, int> ARCHIVE_DEPARTMENTS_STORAGES_HEIRARCHIES
        { get; set; }

        public Departments()
        {
            InitializeComponent();

            btnAddNew.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(btnAddNew_ItemClick);
            btnSaveUpdate.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(btnSaveUpdate_ItemClick);
            btnDeleteItem.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(btnDeleteItem_ItemClick);
            btnRefresh.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(btnRefresh_ItemClick);

            ARCHIVE_DEPARTMENTS = new List<DAL.Database.ARCHIVE_DEPARTMENT>();

            //Load storage medias
            ARCHIVE_DEPARTMENTS_STORAGES_HEIRARCHIES = new Dictionary<int, int>();
            comboDepartmentStorageMedia.Properties.Items.BeginUpdate();
            comboDepartmentStorageMedia.Properties.Items.Clear();
            int i = 0;
            PRO_DOCSDatabaseDataContext.proc_ARCHIVE_DEPARTMENTS_STORAGES_HEIRARCHIESLoadAll().ToList().ForEach(new Action<PRO_DOCS.DAL.Database.proc_ARCHIVE_DEPARTMENTS_STORAGES_HEIRARCHIESLoadAllResult>(delegate(PRO_DOCS.DAL.Database.proc_ARCHIVE_DEPARTMENTS_STORAGES_HEIRARCHIESLoadAllResult _sTORAGE_HEIRARCHY)
            {
                ARCHIVE_DEPARTMENTS_STORAGES_HEIRARCHIES.Add(i, _sTORAGE_HEIRARCHY.ARCHIVE_DEPARTMENT_STORAGE_HEIRARCHY_ID);
                comboDepartmentStorageMedia.Properties.Items.Add(_sTORAGE_HEIRARCHY.ARCHIVE_DEPARTMENT_STORAGE_HEIRARCHY_NAME);
                i++;
            }));

            comboDepartmentStorageMedia.Properties.Items.EndUpdate();
            comboDepartmentStorageMedia.SelectedIndex = -1;
            //Load document types
            try
            {
                PRO_DOCSDatabaseDataContext.proc_ARCHIVE_DOCUMENT_TYPESLoadAll().ToList().ForEach(new Action<PRO_DOCS.DAL.Database.proc_ARCHIVE_DOCUMENT_TYPESLoadAllResult>(delegate(PRO_DOCS.DAL.Database.proc_ARCHIVE_DOCUMENT_TYPESLoadAllResult _dOCUMENT_TYPE)
                {
                    CheckedListBoxItem listViewItem = new CheckedListBoxItem();
                    listViewItem.Value = _dOCUMENT_TYPE.ARCHIVE_DOCUMENT_TYPE_ID.ToString();
                    listViewItem.Description = _dOCUMENT_TYPE.ARCHIVE_DOCUMENT_TYPE_NAME;
                    lstDocumentTypes.Items.Add(listViewItem);
                }));
            }
            catch { }
            //Load ARCHIVE DEPARTMENTS
            RELOAD_ALL_ARCHIVE_DEPARTMENTS();
        }

        void btnRefresh_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            RELOAD_ALL_ARCHIVE_DEPARTMENTS();
        }

        void btnDeleteItem_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {

            if (CURRENT_SELECTED_ARCHIVE_DEPARTMENT.ARCHIVE_DEPARTMENT_ID > 0)
            {
                try
                {
                    PRO_DOCSDatabaseDataContext.proc_ARCHIVE_DEPARTMENTSDelete(CURRENT_SELECTED_ARCHIVE_DEPARTMENT.ARCHIVE_DEPARTMENT_ID);

                    gridView1.DeleteSelectedRows();
                }
                catch
                {
                    XtraMessageBox.Show("The current archive department cannot be deleted as it is already used in another transaction(s)", "Action denied", MessageBoxButtons.OK, MessageBoxIcon.Information);

                }

            }

        }

        void btnSaveUpdate_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            dxErrorProvider1.ClearErrors();
            bool has_department_name = !string.IsNullOrEmpty(txtDepartmentName.Text);
            bool has_archive_storage = comboDepartmentStorageMedia.SelectedIndex > -1;
            if (has_archive_storage && has_department_name)
            {

                long? aRCHIVE_DEPARTMENT_ID = 0;
                if (CURRENT_SELECTED_ARCHIVE_DEPARTMENT.ARCHIVE_DEPARTMENT_ID > 0) //update
                {
                    aRCHIVE_DEPARTMENT_ID = CURRENT_SELECTED_ARCHIVE_DEPARTMENT.ARCHIVE_DEPARTMENT_ID;

                    PRO_DOCSDatabaseDataContext.proc_ARCHIVE_DEPARTMENTSUpdate
                        (
                            aRCHIVE_DEPARTMENT_ID.Value,
                            txtDepartmentName.Text,
                            txtDepartmentDescription.Text,
                            ARCHIVE_DEPARTMENTS_STORAGES_HEIRARCHIES[comboDepartmentStorageMedia.SelectedIndex],
                            !chkIsValid.Checked
                        );

                    gridView1.SetRowCellValue(gridView1.FocusedRowHandle, gcDepartmentName, txtDepartmentName.Text);
                    gridView1.SetRowCellValue(gridView1.FocusedRowHandle, gcDepartmentDescription, txtDepartmentDescription.Text);
                    gridView1.SetRowCellValue(gridView1.FocusedRowHandle, gcStorageHeirarchy, comboDepartmentStorageMedia.Text);
                    gridView1.SetRowCellValue(gridView1.FocusedRowHandle, gcIsValid, !chkIsValid.Checked);

                    SAVE_ARCHIVE_DEPARTMENT_DOCUMENT_TYPES(aRCHIVE_DEPARTMENT_ID.Value);

                    //save permitted user roles
                    ucPermittedUserRoles1.SAVE_PERMITTED_USER_ROLES(aRCHIVE_DEPARTMENT_ID.Value, Guid.Empty, 0);
                    //save permitted login users
                    ucPermittedLoginUsers1.SAVE_PERMITTED_LOGIN_USERS(aRCHIVE_DEPARTMENT_ID.Value, Guid.Empty, 0);
                    //save the denied login users
                    ucDeniedLoginUsers1.SAVE_DENIED_LOGIN_USERS(aRCHIVE_DEPARTMENT_ID.Value, Guid.Empty, 0);
                }
                else
                {
                    PRO_DOCSDatabaseDataContext.proc_ARCHIVE_DEPARTMENTSInsert
                        (
                            ref aRCHIVE_DEPARTMENT_ID,
                            txtDepartmentName.Text,
                            txtDepartmentDescription.Text,
                            ARCHIVE_DEPARTMENTS_STORAGES_HEIRARCHIES[comboDepartmentStorageMedia.SelectedIndex],
                            !chkIsValid.Checked
                        );
                    SAVE_ARCHIVE_DEPARTMENT_DOCUMENT_TYPES(aRCHIVE_DEPARTMENT_ID.Value);
                    //save permitted user roles
                    ucPermittedUserRoles1.SAVE_PERMITTED_USER_ROLES(aRCHIVE_DEPARTMENT_ID.Value, Guid.Empty, 0);
                    //save permitted login users
                    ucPermittedLoginUsers1.SAVE_PERMITTED_LOGIN_USERS(aRCHIVE_DEPARTMENT_ID.Value, Guid.Empty, 0);
                    //save the denied login users
                    ucDeniedLoginUsers1.SAVE_DENIED_LOGIN_USERS(aRCHIVE_DEPARTMENT_ID.Value, Guid.Empty, 0);

                    RELOAD_ALL_ARCHIVE_DEPARTMENTS();
                }

                CURRENT_SELECTED_ARCHIVE_DEPARTMENT = (from department in PRO_DOCSDatabaseDataContext.ARCHIVE_DEPARTMENTs
                                                       where department.ARCHIVE_DEPARTMENT_ID.Equals(aRCHIVE_DEPARTMENT_ID.Value)
                                                       select department).FirstOrDefault();

            }
            else
            {
                dxErrorProvider1.SetError(txtDepartmentName, BLL.WIN.Properties.ErrorProviderMessages.Default.InputLeftBlank.Replace("{name}", "Department name"));
                dxErrorProvider1.SetError(comboDepartmentStorageMedia, BLL.WIN.Properties.ErrorProviderMessages.Default.InputLeftBlank.Replace("{name}", "Department storage"));
            }
        }

        private void SAVE_ARCHIVE_DEPARTMENT_DOCUMENT_TYPES(long aRCHIVE_DEPARTMENT_ID)
        {
            //1. delete previous saved
            PRO_DOCSDatabaseDataContext.proc_ARCHIVE_DEPARTMENT_DOCUMENT_TYPESDeleteByARCHIVE_DEPARTMENT_ID(aRCHIVE_DEPARTMENT_ID);
            //2. Save new data
            for (int i = 0; i < lstDocumentTypes.Items.Count; i++)
            {
                if (lstDocumentTypes.GetItemChecked(i))
                {
                    PRO_DOCSDatabaseDataContext.proc_ARCHIVE_DEPARTMENT_DOCUMENT_TYPESInsert
                        (aRCHIVE_DEPARTMENT_ID,
                        Convert.ToInt64(lstDocumentTypes.GetDisplayItemValue(i).ToString()),
                        false);
                }
            }
        }

        void btnAddNew_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            CLEAR_DEPARTMENT_TABS();
        }


        private void gridView1_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            CLEAR_DEPARTMENT_TABS();

            if (e.FocusedRowHandle > -1)
            {
                CURRENT_SELECTED_ARCHIVE_DEPARTMENT = gridView1.GetFocusedRow() as DAL.Database.ARCHIVE_DEPARTMENT;
                CURRENT_SELECTED_ARCHIVE_DEPARTMENT = (from department in PRO_DOCSDatabaseDataContext.ARCHIVE_DEPARTMENTs
                                                       where department.ARCHIVE_DEPARTMENT_ID.Equals(CURRENT_SELECTED_ARCHIVE_DEPARTMENT.ARCHIVE_DEPARTMENT_ID)
                                                       select department).FirstOrDefault();
                //1. GET GENERAL INFO
                GET_GENERAL_INFO();
                //2. GET DEPARTMENT DOCUMENT TYPES
                GET_DEPARTMENT_DOCUMENT_TYPES();
                //3. GET DEPARTMENT AVAILABLE ROLES
                GET_DEPARTMENT_AVAILABLE_ROLES();
                //4. GET DEPARTMENT AVAILABLE USERS
                GET_DEPARTMENT_AVAILABLE_USERS();
                //5. GET DEPARTMENT DENIED USERS
                GET_DEPARTMENT_DENIED_USERS();
            }
        }

        private void CLEAR_DEPARTMENT_TABS()
        {
            CURRENT_SELECTED_ARCHIVE_DEPARTMENT = new DAL.Database.ARCHIVE_DEPARTMENT();
            //1. CLEAR GENERAL INFO
            CLEAR_GENERALNFO();
            //2. CLEAR DEPARTMENT DOCUMENT TYPES
            lstDocumentTypes.UnCheckAll();
        }

        private void CLEAR_GENERALNFO()
        {
            txtDepartmentName.Text = string.Empty;
            chkIsValid.Checked = false;
            txtDepartmentDescription.Text = string.Empty;
            comboDepartmentStorageMedia.Text = string.Empty;
        }

        private void GET_DEPARTMENT_DENIED_USERS()
        {
            ucDeniedLoginUsers1.LOAD_DENIED_LOGIN_USERS(Security.ucBaseSecurity.SecurityOptions.DepartmentsSecurity, CURRENT_SELECTED_ARCHIVE_DEPARTMENT.ARCHIVE_DEPARTMENT_ID, Guid.Empty, 0);
        }

        private void GET_DEPARTMENT_AVAILABLE_USERS()
        {
            ucPermittedLoginUsers1.LOAD_PERMITTED_LOGIN_USERS(Security.ucBaseSecurity.SecurityOptions.DepartmentsSecurity, CURRENT_SELECTED_ARCHIVE_DEPARTMENT.ARCHIVE_DEPARTMENT_ID, Guid.Empty, 0);
        }

        private void GET_DEPARTMENT_AVAILABLE_ROLES()
        {

            ucPermittedUserRoles1.LOAD_PERMITTED_USER_ROLES(Security.ucBaseSecurity.SecurityOptions.DepartmentsSecurity, CURRENT_SELECTED_ARCHIVE_DEPARTMENT.ARCHIVE_DEPARTMENT_ID, Guid.Empty, 0);
        }

        private void GET_DEPARTMENT_DOCUMENT_TYPES()
        {
            lstDocumentTypes.UnCheckAll();

            Dictionary<string, DAL.Database.ARCHIVE_DEPARTMENT_DOCUMENT_TYPE> aRCHIVE_DEPARTMENT_DOCUMENT_TYPES = CURRENT_SELECTED_ARCHIVE_DEPARTMENT.ARCHIVE_DEPARTMENT_DOCUMENT_TYPEs.ToDictionary(k => k.ARCHIVE_DEPARTMENT_DOCUMNET_TYPE_ID.ToString(), v => v);
            for (int i = 0; i < lstDocumentTypes.Items.Count; i++)
            {
                bool checked_status = aRCHIVE_DEPARTMENT_DOCUMENT_TYPES.ContainsKey(lstDocumentTypes.Items[i].Value.ToString());
                lstDocumentTypes.SetItemChecked(i, checked_status);
            }
        }

        private void GET_GENERAL_INFO()
        {
            txtDepartmentName.Text = CURRENT_SELECTED_ARCHIVE_DEPARTMENT.ARCHIVE_DEPARTMENT_NAME;
            chkIsValid.Checked = !CURRENT_SELECTED_ARCHIVE_DEPARTMENT.IS_DELETED.Value;
            txtDepartmentDescription.Text = CURRENT_SELECTED_ARCHIVE_DEPARTMENT.ARCHIVE_DEPARTMENT_DESCRIPTION;
            comboDepartmentStorageMedia.Text = CURRENT_SELECTED_ARCHIVE_DEPARTMENT.ARCHIVE_DEPARTMENTS_STORAGES_HEIRARCHy.ARCHIVE_DEPARTMENT_STORAGE_HEIRARCHY_NAME;
        }

        private void Departments_Load(object sender, EventArgs e)
        {

        }

        public DAL.Database.ARCHIVE_DEPARTMENT CURRENT_SELECTED_ARCHIVE_DEPARTMENT { get; set; }
    }
}
